import { App, createApp } from "vue";
import _App from "./App.vue";
import router from "./router";
import {
  renderWithQiankun,
  qiankunWindow,
  QiankunProps,
} from "vite-plugin-qiankun/dist/helper";
import { createPinia } from "pinia";
import { useUserStore } from "@/store/user";

let app: App<Element>;
const render = (props: QiankunProps = {}) => {
  const { container, path } = props;
  app = createApp(_App);
  app.use(router);
  app.use(createPinia());
  const mountNode = container ? container.querySelector("#app") : "#app";
  if (mountNode) {
    app.mount(mountNode);
  }

  if (path) {
    router.push(props.path);
  }
};

type User = {
  name?: string;
  gender?: string;
  age?: number;
  phone?: string;
};

function changeUserListener(e: Event) {
  const { name, gender, age, phone } = (e as CustomEvent<User>).detail;
  console.log(`child1收到主应用传递的数据：${name}-${gender}-${age}-${phone}`);

  const userStore = useUserStore();
  userStore.setUserInfo({
    name,
    gender,
    age,
    phone,
  });
}

const initQianKun = () => {
  renderWithQiankun({
    bootstrap() {
      console.log("微应用：bootstrap");
    },
    mount(props) {
      // 获取主应用传入数据
      console.log("微应用：mount", props);
      render(props);
      qiankunWindow.addEventListener("CHANGE_USER", changeUserListener);
    },
    unmount(props) {
      console.log("微应用：unmount", props);
      app.unmount();
      qiankunWindow.removeEventListener("CHANGE_USER", changeUserListener);
    },
    update(props) {
      console.log("微应用：update", props);
    },
  });
};
qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render(); // 判断是否使用 qiankun ，保证项目可以独立运行
